use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tauri::command;

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpRequest {
    pub url: String,
    pub method: Option<String>, // GET, POST, PUT, DELETE
    pub headers: Option<HashMap<String, String>>,
    pub body: Option<String>,
    pub timeout: Option<u64>, // 超时时间（秒）
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpResponse {
    pub status: u16,
    pub headers: HashMap<String, String>,
    pub body: String,
    pub success: bool,
}

#[command]
pub async fn http_request(request: HttpRequest) -> Result<HttpResponse, String> {
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(request.timeout.unwrap_or(30)))
        .build()
        .map_err(|e| format!("创建HTTP客户端失败: {}", e))?;

    let method = request.method.as_deref().unwrap_or("GET").to_uppercase();

    let mut req_builder = match method.as_str() {
        "GET" => client.get(&request.url),
        "POST" => client.post(&request.url),
        "PUT" => client.put(&request.url),
        "DELETE" => client.delete(&request.url),
        "PATCH" => client.patch(&request.url),
        _ => return Err(format!("不支持的HTTP方法: {}", method)),
    };

    // 添加请求头
    if let Some(headers) = request.headers {
        for (key, value) in headers {
            req_builder = req_builder.header(&key, &value);
        }
    }

    // 添加请求体
    if let Some(body) = request.body {
        req_builder = req_builder.body(body);
    }

    // 发送请求
    match req_builder.send().await {
        Ok(response) => {
            let status = response.status().as_u16();
            let success = response.status().is_success();

            // 获取响应头
            let mut headers = HashMap::new();
            for (key, value) in response.headers() {
                if let Ok(value_str) = value.to_str() {
                    headers.insert(key.to_string(), value_str.to_string());
                }
            }

            // 获取响应体
            match response.text().await {
                Ok(body) => Ok(HttpResponse {
                    status,
                    headers,
                    body,
                    success,
                }),
                Err(e) => Err(format!("读取响应体失败: {}", e)),
            }
        }
        Err(e) => Err(format!("HTTP请求失败: {}", e)),
    }
}

// 简化的GET请求方法
#[command]
pub async fn http_get(url: String, headers: Option<HashMap<String, String>>) -> Result<String, String> {
    let request = HttpRequest {
        url,
        method: Some("GET".to_string()),
        headers,
        body: None,
        timeout: Some(30),
    };

    match http_request(request).await {
        Ok(response) => {
            if response.success {
                Ok(response.body)
            } else {
                Err(format!("HTTP请求失败，状态码: {}", response.status))
            }
        }
        Err(e) => Err(e),
    }
}

// 简化的POST请求方法
#[command]
pub async fn http_post(
    url: String,
    body: Option<String>,
    headers: Option<HashMap<String, String>>,
) -> Result<String, String> {
    let request = HttpRequest {
        url,
        method: Some("POST".to_string()),
        headers,
        body,
        timeout: Some(30),
    };

    match http_request(request).await {
        Ok(response) => {
            if response.success {
                Ok(response.body)
            } else {
                Err(format!("HTTP请求失败，状态码: {}", response.status))
            }
        }
        Err(e) => Err(e),
    }
}